#include <stdarg.h>
#include "stringutils.h"
using namespace std;

#include "error.h"


void string_strip(string* s)
{
  static const char* empties = " \t\n\r";
  int b = s->find_first_not_of(empties);
  if (b == -1) {
    *s = string();
    return;
  }
  int e = s->find_last_not_of(empties);
  *s = string(*s, b, e + 1 - b);
}

void string_strip(vector<string>* vs)
{
  for (vector<string>::size_type i = 0; i < vs->size(); i++) {
    string_strip(&((*vs)[i]));
  }
}

void string_split(const char* s_, vector<string>* out, const string& del)
{
  string s(s_);
  string::size_type cut_at;
  while ((cut_at = s.find_first_of(del)) != string::npos) {
    if (cut_at > 0) {
      string ss(s, 0, cut_at);
      out->push_back(ss);
    }
    s = s.substr(cut_at + del.size());
  }
  if (s.length() > 0) out->push_back(s);
}

pair<string, string> string_split_to_pair(const char* s_, const string& del)
{
  string s(s_);
  string::size_type cut_at = s.find_first_of(del);
  if (cut_at != string::npos) {
    return make_pair(s.substr(0, cut_at), s.substr(cut_at + del.size()));
  }
  return make_pair(s, "");
}

void string_replace(string* source, const string& find, const string& replace)
{
  size_t j;
  while ((j = source->find(find)) != string::npos) {
    source->replace(j, find.length(), replace);
  }
}

string sfmt(const char* fmt, ...)
{
  va_list ap;
  char buf[10240];
  va_start(ap, fmt);
  int r = vsnprintf(buf, sizeof buf, fmt, ap);
  va_end(ap);
  if (r < 0 && r >= int(sizeof buf)) {
    throw Error(__FILE__, __LINE__, "sfmt error");
  }
  return string(buf);
}
